/**
 * All rights Reserved, Designed By OprCalf
 * Copyright:    Copyright(C) 2016-2020
 * Company       LengYin Ltd.
 */

package com.platform.gateway.common.request;

import javax.annotation.Resource;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

/**
 * @projectName:  platform-gateway
 * @package:      com.platform.gateway.common.request
 * @className:    GetRequest.java
 * @description:  Get请求
 * @author:       OprCalf
 * @date:         2020年3月27日
 */
@Service
@SuppressWarnings("deprecation")
public class GetRequest extends Request {

    @Resource(name = "balanceTemplate")
    private RestTemplate balanceTemplate;

    @Resource(name = "singleTemplate")
    private RestTemplate singleTemplate;

    /**
     * 发送请求到服务端,初始化head里面的user为空
     * @author OprCalf
     * @param serviceAdd
     * @param servicePath
     * @param params
     * @return JSONObject
     */
    @HystrixCommand(fallbackMethod = "failNullUserForJson")
    public JSONObject getNullUserForJson(String serviceAdd, String servicePath) {
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        final HttpEntity<Object> requestEntity = new HttpEntity<>("", headers);
        final ResponseEntity<JSONObject> response = balanceTemplate.exchange(serviceAdd + servicePath, HttpMethod.GET,
                requestEntity,
                JSONObject.class);
        return JSONObject.parseObject(JSONObject.toJSONString(response.getBody(), Request.filter));
    }

    /**
     * 断路器：发送请求到服务端,初始化head里面的user为空
     * @author OprCalf
     * @date 2019年5月22日
     * @return String
     */
    public JSONObject failNullUserForJson(String serviceAdd, String servicePath) {
        return JSON.parseObject(returnError("请求超时,请稍后再试...").toString());
    }

}
